<!-- 信谊下发移库指令编辑弹窗 -->
<template>
  <div>
  <el-dialog
    :title="isUpdate?'修改信谊移库指令':'添加信谊移库指令'"
    :visible="visible"
    width="80%"
    :destroy-on-close="true"
    :lock-scroll="false"
    @open="initForm"
    :close-on-click-modal="false"
    @update:visible="updateVisible">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="82px">
      <el-row>
        <el-col :lg="12" :md="12">
          <el-form-item label-width="92px"
            label="移库指令号:"
            prop="name">
            <el-input
              :maxlength="20"
              v-model="form.orderno"
              disabled
              placeholder="移库指令号自动生成"
              clearable/>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="6">
          <el-form-item
            label="组织:"
            prop="name">
            <el-select
              clearable
              v-model="form.companycode"
              size="small"
              placeholder="-请选择组织-"
              class="ele-block">
              <el-option v-for="item in codeList" :key="item.code" :label="item.name" :value="item.code"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="6">
          <el-form-item
            label="业务类型:"
            prop="name">
            <el-input
              :maxlength="20"
              disabled
              v-model="form.ordertype"
              placeholder="请输入业务类型"
              clearable/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :lg="12" :md="12">
          <el-form-item label-width="92px"
            label="单据日期:"
            prop="name">
            <el-date-picker disabled v-model="form.orderdate" type="date" format='yyyy-MM-dd' value-format='yyyy-MM-dd' placeholder="选择日期" clearable class="ele-fluid"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :lg="6" :md="6">
          <el-form-item
            label="仓库位置:"
            prop="name">
            <el-select
              clearable
              v-model="form.plant"
              size="small"
              placeholder="-请选择仓库位置-"
              class="ele-block">
              <el-option v-for="item in plantList" :key="item.plant" :label="item.plantname" :value="item.plant"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
        <el-form-item label="备注:" label-width="92px">
          <el-input
            :rows="2"
            clearable
            type="textarea"
            :maxlength="200"
            v-model="form.remark"
            placeholder="请输入备注"/>
        </el-form-item>
    </el-form>
    <ele-pro-table
      ref="table"
      :where="where"
      :datasource="itemList"
      :columns="columns"
      :toolbar="true"
      :need-page="false"
      :selection.sync="selection"
      height="calc(100vh - 420px)">
      <template slot="tolocation" slot-scope="{row}">
<!--        <el-input-->
<!--          :maxlength="20"-->
<!--          v-model="row.tolocation"-->
<!--          placeholder=""-->
<!--          clearable/>-->
        <el-select
          clearable
          v-model="row.tolocation"
          size="small"
          placeholder="-请选择-"
          class="ele-block">
          <el-option v-for="item in bincodeList" :key="item.bincode" :label="item.bindesc" :value="item.bincode"/>
        </el-select>

      </template>
      <template slot="qty" slot-scope="{row}">
        <el-input
          :maxlength="20"
          v-model="row.qty"
          placeholder=""
          clearable/>
      </template>
      <!-- 表头工具栏 -->
      <template slot="toolbar">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          class="ele-btn-icon"
          @click="addItem"
          >添加
        </el-button>
        <el-button
          size="small"
          type="danger"
          icon="el-icon-delete"
          class="ele-btn-icon"
          @click="removeitem"
          >删除
        </el-button>
      </template>
      <!-- 操作列 -->
      <template slot="action" slot-scope="{row}">
        <el-link
          type="primary"
          :underline="false"
          icon="el-icon-edit"
          @click="openEdit(row)"
          v-if="permission.includes('sys:kdlsinegoodsmovement:edit')">修改
        </el-link>
        <el-popconfirm
          class="ele-action"
          title="确定要删除此信谊下发移库指令吗？"
          @confirm="remove(row)">
          <el-link
            type="danger"
            slot="reference"
            :underline="false"
            icon="el-icon-delete"
            v-if="permission.includes('sys:kdlsinegoodsmovement:delete')">删除
          </el-link>
        </el-popconfirm>
      </template>
    </ele-pro-table>

    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button
        type="primary"
        @click="save"
        :loading="loading">保存
      </el-button>
    </div>
  </el-dialog>
    <SelectInv
      :data="current"
      :visible.sync="showSelectInv"
      @done="loadInv"/>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import SelectInv from './select-inv'
import setting from "@/config/setting";
export default {
  name: 'KdlSineGoodsmovementEdit',
  components: {SelectInv},
  props: {
    // 弹窗是否打开
    visible: Boolean,
    billtype: String,
    // 修改回显的数据
    data: Object
  },
  computed: {
    ...mapGetters(["permission"]),
  },
  data() {
    return {
      url:'',
      where:{},
      itemList:[],
      codeList:[],
      plantList:[],
      bincodeList:[],
      selection:[],
      item:{
        itemno:'',
        invname:'',
        vendorbatch:'',
        manufacturedate:'',
        expireddate:'',
        qty:'',
        fromlocation:'',
        storname:'',
        tolocation:'',
        tostorname:'',
        boxflag:'',
        boxno:''
      },
      columns:[
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center',
          fixed: "left"
        },
        {
          prop: 'itemno',
          label: '产品编码',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'invname',
          label: '产品名称',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'left'
        },
        {
          prop: 'vendorbatch',
          label: '批号',
          showOverflowTooltip: true,
          minWidth: 130,
          align: 'center'
        },
        {
          prop: 'manufacturedate',
          label: '生产日期',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'expireddate',
          label: '有效期',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'qty',
          label: '数量',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center',
          slot:'qty'
        },
        {
          prop: 'fromlocation',
          label: '移出库位',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'storname',
          label: '库位名称',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
        {
          prop: 'tolocation',
          label: '移入库位',
          showOverflowTooltip: true,
          minWidth: 160,
          align: 'center',
          slot:'tolocation'
        },
        {
          prop: 'boxflag',
          label: '箱型',
          showOverflowTooltip: true,
          minWidth: 60,
          align: 'center'
        },
        {
          prop: 'boxno',
          label: '箱号',
          showOverflowTooltip: true,
          minWidth: 100,
          align: 'center'
        },
      ],
      current: null,
      // 表单数据
      form: {
        companycode:'',
        plant:'',
        orderdate: new Date(),
        ordertype: 'GM',
        billtype: ''
      },
      // 表单验证规则
      rules: {
        orderno: [
          {required: true, message: '请输入移库指令号', trigger: 'blur'}
        ],
        ordertype: [
          {required: true, message: '请输入业务类型', trigger: 'blur'}
        ],
        orderdate: [
          {required: true, message: '请输入单据日期', trigger: 'blur'}
        ],
        plant: [
          {required: true, message: '请输入工厂', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入备注', trigger: 'blur'}
        ],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showSelectInv:false,
    };
  },
  mounted() {
    this.getOrgList();
    this.getPlantList();
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
        console.log(this.data);
        this.loaddata(this.data.id);
      } else {
        this.form = {};
        this.initForm();
        this.isUpdate = false;
      }
    }
  },
  methods: {
    initForm(){
      if(!this.isUpdate) {
        //console.log("init");
        this.form.ordertype = 'GM';
        this.form.billtype = setting.takeItem("move_billtype");
        this.form.orderdate = new Date();
        this.itemList=[];
        //console.log(this.form);
      }
    },
    removeitem(){
      if(this.selection.length==0) return;
      for(let newitem of this.selection)
      {
        var index = this.itemList.findIndex(s=>(s.itemno == newitem.itemno && s.vendorbatch==newitem.vendorbatch && s.fromlocation==newitem.fromlocation));
        this.itemList.splice(index,1);
      }

    },
    /**
     * 获取组织列表
     */
    getOrgList() {
      this.$http.get('/dictdata/index?dictId=19&page=1&limit=1000').then(res => {
        this.codeList = res.data.data.records;
        if(this.codeList.length>0){
          this.form.companycode = this.codeList[0].code;
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取仓库列表
     */
    getPlantList() {
      this.$http.get('/kdl/plantlist').then(res => {
        this.plantList = res.data.data;
        if(this.plantList.length>0){
          this.form.plant = this.plantList[0].plant;
          this.getBincodeList();
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取仓库列表
     */
    getBincodeList() {
      this.$http.get('/kdl/bincodelist/'+this.form.plant).then(res => {
        this.bincodeList = res.data.data;
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    addItem(){
      //let newitem = Object.assign({},this.item);
      //this.itemList.push(newitem);
      this.showSelectInv=true;
    },
    removeItem(){},
    loadInv(list){
      for(let i=0;i<list.length;i++)
      {
        let newitem = Object.assign({},this.item);
        newitem.itemno = list[i].invcode;
        newitem.invname = list[i].invname;
        newitem.vendorbatch = list[i].vlotno;
        newitem.fromlocation  = list[i].storcode;
        newitem.storname = list[i].storname;
        newitem.manufacturedate  = list[i].dprodate;
        newitem.expireddate  = list[i].vinvaliddate;
        newitem.qty  = list[i].nonhandnum;
        newitem.boxflag = list[i].boxflag;
        newitem.boxno = list[i].boxno;
        const index = this.itemList.findIndex(s=>(s.itemno == newitem.itemno && s.vendorbatch==newitem.vendorbatch && s.fromlocation==newitem.fromlocation && s.boxflag==newitem.boxflag));
        if(index <0) {
          this.itemList.push(newitem);
        }
        else {
          let row = this.itemList.find(s=>(s.itemno == newitem.itemno && s.vendorbatch==newitem.vendorbatch && s.fromlocation==newitem.fromlocation && s.boxflag==newitem.boxflag));
          row.qty = Number(row.qty)+Number(newitem.qty);
        }

      }
    },
    loaddata(id){
      this.$http.get('/kdlsinegoodsmovement/detail/'+id).then(res=>{
        this.itemList = res.data.data;
      });
    },

    /* 保存编辑 */
    save() {
      if(!this.form.companycode){
        this.$message.info("请选择组织");
        return;
      }
      if(!this.form.plant){
        this.$message.info("请选择仓库位置");
        return;
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true;
          let param = {
            goodsmovement: this.form,
            goodsmovementLines: this.itemList
          }
          this.$http[this.isUpdate ? 'post' : 'post'](this.isUpdate ? '/kdlsinegoodsmovement/update' : '/kdlsinegoodsmovement/create', param).then(res => {
            this.loading = false;
            if (res.data.code === 0) {
              this.$message.success(res.data.msg);
              if (!this.isUpdate) {
                this.form = {};
              }
              this.updateVisible(false);
              this.$emit('done');
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            this.loading = false;
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit('update:visible', value);
    }
  }
}
</script>

<style scoped>
</style>
